<script setup>
import { defineEmits, reactive, ref, defineProps, watch } from "vue"
import { closeData } from '@/utils/user.js'
import { md5Encryption } from '@/utils/encryption.js'
import { showToast } from "vant"
import { isValidPhoneNumber } from '@/utils/index.js'
import api from '@/api/index.js'

const emit = defineEmits(['emitCodeLogin'])
const props = defineProps({
  deleteCode: Number
})

watch(() => props.deleteCode, () => {
  loginFrom.code = ''
})

const loginFrom = reactive({
  username: '',
  code: ''
})
const getCodeLoading = ref(false)
const time = ref(0)
const getCode = () => {
  closeData()
  const phone = loginFrom.username
  if (!phone || !isValidPhoneNumber(phone)) {
    showToast('请输入正确的手机号码')
    return
  }
  if (!getCodeLoading.value) {
    getCodeLoading.value = true
    api.getLoginCode({
      telephone: phone
    }).then(() => {
      showToast('短信验证码获取成功，请注意短信信息')
      time.value = 60
      const timer = setInterval(() => {
        if (time.value === 0) {
          clearInterval(timer)
        } else {
          time.value -= 1
        }
      }, 1000)
    }).finally(() => {
      getCodeLoading.value = false
    })
  }
}

const updateInput = () => {
  emit('emitCodeLogin', loginFrom)
}
</script>

<template>
  <!-- 可以使用 CellGroup 作为容器 -->
  <div class="box">
    <van-cell-group class="input_item" inset>
      <van-field v-model="loginFrom.username" @update:model-value="updateInput" type="tel" placeholder="请输入手机号" />
    </van-cell-group>
    <van-cell-group class="input_item" inset>
      <van-field v-model="loginFrom.code" @update:model-value="updateInput" type="digit" placeholder="请输入验证码" >
        <template #button>
          <template v-if="!getCodeLoading">
            <div v-if="time" class="code_time">{{time}}秒后重新获取</div>
            <div v-else class="get_code" @click="getCode">获取验证码</div>
          </template>
          <van-loading v-else type="spinner" size="20px" />
        </template>
      </van-field>
    </van-cell-group>
  </div>

</template>

<style scoped lang="scss">
:deep(.van-cell-group--inset) {
  margin: 0;
  height: 5rem;
}
:deep(.van-cell) {
  padding: 0 1rem;
  line-height: 5rem;
  font-size: 1.6rem;
}
.box{
  margin: 4rem 3rem 0 3rem;
  .input_item{
    margin-bottom: 2rem;
    .code_time{
      font-size: 1.6rem;
      color: #cccccc;
    }
    .get_code{
      font-size: 1.6rem;
      color: var(--van-primary-color);
    }
  }
}
</style>